import SECRET from '../../utils/secret'
import CATEGORIES from '../../utils/categories'

Page({
  data: {},
  onLoad: function (options) {
    console.log(options)
    this.setData({
      type: CATEGORIES,
      classify: options.classify,
      indexA: options.account
    })
    this.init()
  },
  async init() {
    const { classify, indexA } = this.data
    let accountArr = wx.getStorageSync(CATEGORIES[classify - 1].name)[indexA]
    const { account = '', name = '', note = '', password = '' } = accountArr
    this.setData({
      account: SECRET.decrypt(account),
      classify: classify,
      index: classify - 1,
      name: SECRET.decrypt(name),
      note: SECRET.decrypt(note),
      password: SECRET.decrypt(password),
    })
  },
  PickerChange(e) {
    let that = this
    this.setData({
      index: e.detail.value,
      classify: that.data.type[e.detail.value].id
    })
  },
  onNameInput(e) {
    const { value } = e.detail
    this.setData({ name: value })
  },
  onAccountInput(e) {
    const { value } = e.detail
    this.setData({ account: value })
  },
  onPasswordInput(e) {
    const { value } = e.detail
    this.setData({ password: value })
  },
  onNoteInput(e) {
    const { value } = e.detail
    this.setData({ note: value })
  },
  async onButtonTap() {
    const { name, account, password, note, classify, } = this.data
    if (!name) {
      wx.showToast({ title: '名称不能为空', icon: 'none' })
    } else {
      wx.showLoading({ title: '保存中...' })
      const cloudData = {}
      if (name) {
        cloudData.name = SECRET.encrypt(name)
      }
      if (account) {
        cloudData.account = SECRET.encrypt(account)
      }
      if (password) {
        cloudData.password = SECRET.encrypt(password)
      }
      if (note) {
        cloudData.note = SECRET.encrypt(note)
      }
      cloudData.classify = classify

      let accountList = wx.getStorageSync(CATEGORIES[classify - 1].name)
      accountList.splice(this.data.indexA, 1);
      accountList.push(cloudData)
      wx.setStorageSync(CATEGORIES[classify - 1].name, accountList)
      wx.hideLoading()
      wx.showToast({ title: '修改成功' })
    }
  },
})